
package wuziqi;

// 通用的连续棋子检查器
class ContinuousWinChecker implements WinChecker {
    @Override
    public boolean checkWin(GameState state, GameConfig config) {
        char[][] board = state.getBoard();
        int lastRow=state.getLastMoveRow();
        int lastCol=state.getLastMoveCol();
        // 没有落子记录，游戏刚开始直接快速判断不会有人获胜。
        if (lastRow == -1 || lastCol == -1) {
            return false;
        }

        char player = board[lastRow][lastCol];
        int size = config.getBoardSize();
        int winCount = config.getWinCount();
        
        // 检查8个方向：水平、垂直、两个对角线
        int[][] directions = {
            {0, 1},  // 水平右
            {1, 0},  // 垂直下
            {1, 1},  // 右下对角线
            {1, -1}  // 左下对角线
        };
        
        for (int[] dir : directions) {
            int count = 1; // 当前位置已经有一个棋子
            
            // 正向检查
            count += countContinuous(board, lastRow, lastCol, dir[0], dir[1], player, size);
            // 反向检查  
            count += countContinuous(board, lastRow, lastCol, -dir[0], -dir[1], player, size);
            
            if (count >= winCount) {
                return true;
            }
        }
        
        return false;
    }
    
    private int countContinuous(char[][] board, int row, int col, int rowDir, int colDir, char player, int size) {
        int count = 0;
        int r = row + rowDir;
        int c = col + colDir;
        
        while (r >= 0 && r < size && c >= 0 && c < size && board[r][c] == player) {
            count++;
            r += rowDir;
            c += colDir;
        }
        
        return count;
    }
}
